from flask import Blueprint, render_template, redirect, make_response, jsonify, session
from flask import request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity, JWTManager, create_refresh_token
from development import SECRETKEY
import jwt
import json
import requests
import development as dp

bp = Blueprint("login_register", __name__, url_prefix='/L_R')
from mongoDb_connection.connection import initDatabase, addData, find_data


@bp.route('/login', methods=['GET', 'POST'])
def login():
    # print(request.form, request.json)
    username = request.json['username']
    password = request.json['password']
    find_json = {
        "username": username,
        "password": password
    }
    db = initDatabase(dp.DATABASE_NAME)
    res_find = find_data(db, find_json, 'one', 'user')
    if not res_find:
        return {"msg": '查询不到信息', "code": 500}, 500
    access_token = create_access_token(identity=username)
    refresh_token = create_refresh_token(identity=username)

    rest = {
        "msg": f"登录成功",
        'token': f"Bearer {access_token}",
        'refresh_token': f"Bearer {refresh_token}",
        'code': 200
    }
    # return jsonify(access_token=access_token), 200
    # return jsonify(rest)
    return json.dumps(rest, ensure_ascii=False), 200


@bp.route('/reg', methods=['GET', 'POST'])
def register():
    print(request.form, request.json)
    username = request.json['username']
    password = request.json['password']
    repassword = request.json['repassword']
    # 数据库操作
    db = initDatabase(dp.DATABASE_NAME)
    add_json = {
        "username": username,
        "password": password,
        "repassword": repassword
    }
    find_json = {
        "username": username
    }
    res_find = find_data(db,find_json, 'one', 'user')
    if res_find:
        return {"msg": 'user already exist', "code": 500}, 500
    res_add = addData(db, add_json, 'user')
    if res_add['res'] == 'fail' :
        return {"msg": 'database error', "code": 500}, 500
    return {"msg": 'add success', "code": 200}, 200


@bp.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    current_user = get_jwt_identity()
    print(current_user)
    # return jsonify({'msg': 'ok'}), 200
    return jsonify({'msg': 'ok'})


# 使用刷新JWT来获取普通JWT  前提是已经调用了 /login 接口 携带 refresh_token请求该接口
@bp.route("/refresh", methods=["POST"])
@jwt_required(refresh=True)
def refresh():
    identity = get_jwt_identity()
    access_token = create_access_token(identity=identity)
    rest = {
        'access_token': f"Bearer {access_token}",
        'code': 200
    }
    return jsonify(rest)
